package com.graduation.smartparkingplatform.Interceptor;

import com.alibaba.fastjson.JSONObject;
import com.graduation.smartparkingplatform.Utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class AdminInterceptor implements HandlerInterceptor {

  /** 在请求处理之前进行调用（Controller方法调用之前） */
  @Override
  public boolean preHandle(
      HttpServletRequest request, HttpServletResponse response, Object handler) {
    //    放行options预检请求
    if (request.getMethod().equals("OPTIONS")) {
      response.setStatus(HttpServletResponse.SC_OK);
      return true;
    }
    // 统一拦截（获取请求头中的Authorization:token）
    String token = request.getHeader("Authorization");
    if (token != null) {
      // 验证身份是否过期
      if (JwtUtils.ItprVerifyToken(token)) {
        return true;
      } else {
        expireLogin(response);
        return false;
      }
    } else {
      Loginisn(response);
      return false;
    }
  }

  /** 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后） */
  @Override
  public void postHandle(
      HttpServletRequest request,
      HttpServletResponse response,
      Object handler,
      ModelAndView modelAndView) {
    //         System.out.println("执行了TestInterceptor的postHandle方法");
  }

  /** 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作） */
  @Override
  public void afterCompletion(
      HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
      throws Exception {
    //    System.out.println("执行了TestInterceptor的afterCompletion方法");

  }
  // 用户未登录返回方法
  private void Loginisn(HttpServletResponse response) {
    PrintWriter writer = null;
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json; charset=utf-8");
    try {
      // 自定义返回类
      Map result = new HashMap();
      result.put("code", 401);
      result.put("message", "用户暂未登录");
      result.put("data", null);
      JSONObject jsonResult = new JSONObject(result);
      writer = response.getWriter();
      //            Map<String, Object> result = PackageReturnResult.returnJson(400, "用户令牌token无效");
      writer.print(jsonResult);
    } catch (IOException e) {
      log.error("AdminInterceptor-Loginisn error:" + e);
      e.printStackTrace();
    } finally {
      if (writer != null) {
        writer.close();
      }
    }
  }
  // 用户身份过期返回方法
  private void expireLogin(HttpServletResponse response) {
    PrintWriter writer = null;
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json; charset=utf-8");
    try {
      // 自定义返回类
      Map result = new HashMap();
      result.put("code", 400);
      result.put("message", "用户令牌token无效");
      result.put("data", null);
      JSONObject jsonResult = new JSONObject(result);
      writer = response.getWriter();
      //            Map<String, Object> result = PackageReturnResult.returnJson(400, "用户令牌token无效");
      writer.print(jsonResult);
    } catch (IOException e) {
      log.error("AdminInterceptor-expireLogin error:" + e);
      e.printStackTrace();
    } finally {
      if (writer != null) {
        writer.close();
      }
    }
  }
}
